#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "campaignform.h"


#include <QDebug>
#include <QFileDialog>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionNew_triggered()
{
    CampaignForm* form = new CampaignForm(this);
    form->create();

    int index = ui->tabWidget->addTab(form, tr("New Campaign"));
    ui->tabWidget->setCurrentIndex(index);
}

void MainWindow::on_actionOpen_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Campaign File"), QDir::currentPath(), tr("Xml Files (*.xml)"));
    if (fileName.isEmpty())
    {
        return;
    }

    CampaignForm* form = new CampaignForm(this);
    if (!form->open(fileName))
    {
        form->deleteLater();
        return;
    }

    int index = ui->tabWidget->addTab(form, tr("[Todo: Campaign Name]"));
    ui->tabWidget->setCurrentIndex(index);

}

void MainWindow::on_actionSave_As_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QDir::currentPath(), tr("Xml Files (*.xml)"));
    if (fileName.isEmpty())
    {
        return;
    }

    CampaignForm* form = qobject_cast<CampaignForm*>(ui->tabWidget->currentWidget());
    if (!form)
    {
        return;
    }

    form->save(fileName);
}

void MainWindow::on_actionSave_triggered()
{
    CampaignForm* form = qobject_cast<CampaignForm*>(ui->tabWidget->currentWidget());
    if (!form)
    {
        return;
    }

    if (form->save())
    {
        return;
    }

    on_actionSave_As_triggered();
}


void MainWindow::on_actionClose_triggered()
{
    on_tabWidget_tabCloseRequested(ui->tabWidget->currentIndex());
}


void MainWindow::on_actionQuit_triggered()
{
    while (ui->tabWidget->count())
    {
        on_tabWidget_tabCloseRequested(0);
    }

    close();
}


void MainWindow::on_tabWidget_tabCloseRequested(int index)
{
    on_actionSave_triggered();
    QWidget* widget = ui->tabWidget->widget(index);
    ui->tabWidget->removeTab(index);
    widget->deleteLater();
}


void MainWindow::on_tabWidget_currentChanged(int index)
{
    Q_UNUSED(index)

    CampaignForm* form = qobject_cast<CampaignForm*>(ui->tabWidget->currentWidget());
    if (!form)
    {
        return;
    }

    QString campaignDir = form->fileInfo().absolutePath();
    QDir::setCurrent(campaignDir);

    ui->menuCampaign->clear();
    ui->menuCampaign->addActions(form->actions());
}


